import React, {useEffect, useState} from 'react';
import {
    Box,
    Button,
    Card,
    CardContent,
    CardHeader,
    Chip,
    Divider,
    FormControl,
    IconButton,
    InputLabel,
    MenuItem,
    Paper, Popover,
    Select,
    Stack,
    styled,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TablePagination,
    TableRow,
    Tooltip,
    Typography
} from "@mui/material";
import CircularProgress from "@mui/material/CircularProgress";
import {DatePicker} from '@mui/x-date-pickers/DatePicker';

import ToggleButton from "@mui/material/ToggleButton";

import PendingIcon from '@mui/icons-material/Pending';
import PaidIcon from '@mui/icons-material/Paid';
import RefreshIcon from '@mui/icons-material/Refresh';
import SearchIcon from '@mui/icons-material/Search';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import ExpandIcon from '@mui/icons-material/Expand';
import CompressIcon from '@mui/icons-material/Compress';

import {Equalizer, HelpOutlineOutlined, QrCode, RestartAlt} from "@mui/icons-material";

import {formatMoney} from "../../utils/math";
import {formatDate, YYYYMMDD} from "../../utils/time";

import dayjs from "dayjs";
import LoadingButton from "@mui/lab/LoadingButton";

import ToggleButtonGroup, {toggleButtonGroupClasses,} from '@mui/material/ToggleButtonGroup';
import PageNavBar from "../common/page-nav-bar";

import {commissions as listCommissions, list, stat as commissionStat} from "../../api/finance/referrer";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import CloseIcon from "@mui/icons-material/Close";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import QRCode from "qrcode.react";
import {useSelector} from "react-redux";
import {generateCode} from "../../utils/referrer";

const TemplateForm = Object.freeze({
    page: 1,
    start: dayjs().startOf('month').startOf('day'),
    end: dayjs().subtract(1, 'day').startOf('day'),
    referrerId: 0,
    paid: false,
    cat: null,
});

const StyledToggleButtonGroup = styled(ToggleButtonGroup)(({theme}) => ({
    [`& .${toggleButtonGroupClasses.grouped}`]: {
        margin: theme.spacing(0.5),
        border: 0,
        borderRadius: theme.shape.borderRadius,
        [`&.${toggleButtonGroupClasses.disabled}`]: {
            border: 0,
        },
    },
    [`& .${toggleButtonGroupClasses.middleButton},& .${toggleButtonGroupClasses.lastButton}`]:
        {
            marginLeft: -1,
            borderLeft: '1px solid transparent',
        },
}));

function Commission({principal = true}) {

    const user = useSelector(state => state.auth.user);

    const [total, setTotal] = useState(0);
    const [page, setPage] = useState(1);
    const [size, setSize] = useState(10);

    const [form, setForm] = useState({...TemplateForm});

    const [loading, setLoading] = useState(false);
    const [commissions, setCommissions] = useState([]);
    const [referrers, setReferrers] = useState([]);


    const [searching, setSearching] = useState(false);
    const [showForm, setShowForm] = useState(true);
    const [dense, setDense] = useState(true);

    const [open, setOpen] = useState(false);
    const [statData, setStatData] = useState({
        pt: null,
        paidSignupCommission: "0.00",
        paidOrderCommission: "0.00",
        unpaidSignupCommission: "0.00",
        unpaidOrderCommission: "0.00",
    });

    const [url, setUrl] = useState('');
    const [qrCodeOpen, setQrCodeOpen] = useState(false);

    const [copyOkOpen, setCopyOkOpen] = useState(false);
    const [anchorEl, setAnchorEl] = useState(null);

    function showQrCode() {
        const code = generateCode(user.id, user.schoolId);
        setUrl(`${process.env.REACT_APP_HOST}/school/${code}`);
        setQrCodeOpen(true);
    }

    function loadCommissions(query) {
        setLoading(true);

        listCommissions({
            ...query,
            start: formatDate(query.start),
            end: formatDate(query.end),
        }).then(data => {

            setTotal(data.total);
            setPage(data.page);
            setSize(data.size);
            setCommissions(data.list);

            setLoading(false);
            setSearching(false);
        });
    }

    function loadReferrers() {
        list().then(data => {
            setReferrers(data);
        });
    }

    useEffect(() => {
        principal && loadReferrers();
        loadCommissions(TemplateForm);
    }, [principal]);

    function handleChange(event) {
        const {name, value} = event.target;
        setForm({...form, [name]: value});
    }

    function stat() {
        commissionStat().then(data => {
            if (data !== null) {
                setStatData({
                    pt: data.pt,
                    paidSignupCommission: formatMoney(data.paidSignupCommission),
                    paidOrderCommission: formatMoney(data.paidOrderCommission),
                    unpaidSignupCommission: formatMoney(data.unpaidSignupCommission),
                    unpaidOrderCommission: formatMoney(data.unpaidOrderCommission)
                });
            }
            setOpen(true);
        });
    }

    return (
        <Box p={4} display="flex" gap={4} flexDirection="column">
            <Card raised sx={{padding: 2, boxSizing: 'border-box', width: '100%'}}>
                <CardHeader
                    title={
                        <Stack direction="row" alignItems="center" spacing={1}>
                            <Typography variant="h5">订单</Typography>
                            {loading && <CircularProgress color="inherit" size={24}/>}
                        </Stack>}
                    action={
                        <Box mr={1}>
                            <IconButton onClick={() => setShowForm(!showForm)}>
                                {showForm ? <VisibilityOffIcon/> : <VisibilityIcon/>}
                            </IconButton>

                            <IconButton onClick={() => setDense(!dense)}>
                                {dense ? <ExpandIcon/> : <CompressIcon/>}
                            </IconButton>

                            <IconButton onClick={() => loadCommissions(form)}><RefreshIcon/></IconButton>

                            <Tooltip title="每天凌晨统计上一天的佣金">
                                <IconButton><HelpOutlineOutlined/></IconButton>
                            </Tooltip>
                        </Box>
                    }/>

                <CardContent>
                    {showForm && <Box mb={4} display="flex" gap={2} alignItems="center" flexWrap="wrap">
                        <DatePicker format={YYYYMMDD} sx={{width: 160}}
                                    label="开始日期" value={form.start}
                                    onChange={v => setForm({...form, start: v})}/>

                        <DatePicker format={YYYYMMDD} sx={{width: 160}}
                                    label="结束日期" name="end" value={form.end}
                                    onChange={v => setForm({...form, end: v})}/>

                        {principal &&
                            <FormControl sx={{width: 160}}>
                                <InputLabel>推广人</InputLabel>
                                <Select value={form.referrerId} label="推广人" name="referrerId"
                                        onChange={handleChange}>
                                    <MenuItem value="0">选择推广人</MenuItem>
                                    <Divider/>
                                    {referrers.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                                </Select>
                            </FormControl>
                        }

                        <Paper
                            elevation={0}
                            sx={{
                                display: 'flex',
                                border: (theme) => `1px solid ${theme.palette.divider}`,
                                flexWrap: 'wrap',
                            }}
                        >
                            <StyledToggleButtonGroup
                                name="cat" value={form.cat} exclusive
                                onChange={(_, newValues) => setForm({...form, cat: newValues})}>
                                <ToggleButton value={"SIGNUP"}>注册佣金</ToggleButton>
                                <ToggleButton value={"ORDER"}>订单佣金</ToggleButton>
                            </StyledToggleButtonGroup>

                            <Divider flexItem orientation="vertical" sx={{mx: 0.5, my: 1}}/>

                            <StyledToggleButtonGroup
                                name="paid" value={form.paid} exclusive
                                onChange={(_, newValues) => setForm({...form, paid: newValues})}>
                                <Tooltip title="未支付" placement="top" arrow>
                                    <ToggleButton value={false}><PendingIcon/></ToggleButton>
                                </Tooltip>
                                <Tooltip title="已支付" placement="top" arrow>
                                    <ToggleButton value={true}><PaidIcon/></ToggleButton>
                                </Tooltip>
                            </StyledToggleButtonGroup>
                        </Paper>

                        <Button startIcon={<RestartAlt/>} variant="contained" color="primary"
                                onClick={() => setForm({...TemplateForm})}>
                            重置
                        </Button>
                        <LoadingButton
                            startIcon={<SearchIcon/>} variant="contained" color="primary"
                            type="submit" loading={searching}
                            loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                            onClick={() => {
                                setSearching(true);
                                const updatedForm = {...form, page: 1};
                                setForm(updatedForm);
                                loadCommissions(updatedForm);
                            }}>
                            查询
                        </LoadingButton>
                        {!principal && (<>
                            <Button variant="contained" color="primary" startIcon={<Equalizer/>} onClick={stat}>
                                统计
                            </Button>
                            <Button variant="contained" color="primary" startIcon={<QrCode/>} onClick={showQrCode}>
                                推广链接
                            </Button>
                        </>)}
                    </Box>
                    }

                    <TableContainer component={Paper}>
                        <Table size={dense ? 'small' : 'medium'}>
                            <TableHead>
                                <TableRow>
                                    <TableCell width={'30px'}>ID</TableCell>
                                    <TableCell>推广人</TableCell>
                                    <TableCell>用户</TableCell>
                                    <TableCell width={'160px'}>类型</TableCell>
                                    <TableCell width={'120px'}>佣金</TableCell>
                                    <TableCell width={'60px'} align={"center"}>支付状态</TableCell>
                                    <TableCell width={'160px'} align={"center"}>时间</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {commissions.map(e => (
                                    <TableRow key={e.id}>
                                        <TableCell component="th" scope="row">{e.id}</TableCell>
                                        <TableCell>{e.name}</TableCell>
                                        <TableCell>{e.username}</TableCell>
                                        <TableCell>{e.cat === 'ORDER' ? "注册佣金" : "订单佣金"}</TableCell>
                                        <TableCell>{formatMoney(e.commission)} 元</TableCell>
                                        <TableCell>
                                            <ToggleButtonGroup disabled value={e.paid}>
                                                <ToggleButton value={false}><PendingIcon/></ToggleButton>
                                                <ToggleButton value={true}><PaidIcon/></ToggleButton>
                                            </ToggleButtonGroup>
                                        </TableCell>
                                        <TableCell>{e.ct}</TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                    {
                        total > size && <TablePagination
                            ActionsComponent={PageNavBar}
                            rowsPerPageOptions={[10]}
                            component="div"
                            count={total}
                            rowsPerPage={size}
                            page={page - 1}
                            labelDisplayedRows={({count, page}) =>
                                `第 ${page + 1} 页，共 ${Math.ceil(total / size)} 页，共 ${count} 条数据`}
                            onPageChange={(event, newPage) => {
                                window.scrollTo(0, 0);
                                const updatedForm = {...form, page: newPage + 1};
                                setForm(updatedForm);
                                loadCommissions(updatedForm);
                            }}
                        />
                    }
                </CardContent>
            </Card>
            {
                !principal && <>
                    <Dialog open={open} onClose={() => setOpen(false)}>
                        <DialogTitle sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                            <Typography variant="title">佣金统计</Typography>
                            <IconButton onClick={() => setOpen(false)}><CloseIcon/></IconButton>
                        </DialogTitle>

                        <Card raised sx={{width: '480px', padding: 0, boxSizing: 'border-box'}}>
                            <CardContent>
                                <Stack p={2} spacing={2} justifyContent="flex-start">
                                    <Typography>已支付{statData.pt ? `（最后一次支付时间：${statData.pt}）` : ""}</Typography>
                                    <Stack direction="row" spacing={1}>
                                        <Chip label={`注册佣金：${statData.paidSignupCommission} 元`}/>
                                        <Chip label={`订单佣金：${statData.paidOrderCommission} 元`}/>
                                    </Stack>
                                    <Typography>未支付</Typography>
                                    <Stack direction="row" spacing={1}>
                                        <Chip label={`注册佣金：${statData.unpaidSignupCommission} 元`}/>
                                        <Chip label={`订单佣金：${statData.unpaidOrderCommission} 元`}/>
                                    </Stack>
                                </Stack>
                            </CardContent>
                        </Card>

                    </Dialog>

                    <Dialog open={qrCodeOpen} onClose={() => setQrCodeOpen(false)}>
                        <DialogTitle sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                            <Typography variant="title">推广链接</Typography>
                            <Box>
                                <IconButton size="small" title="点击复制" onClick={(event) => {
                                    const button = event.currentTarget;
                                    navigator.clipboard.writeText(url)
                                        .then(() => {
                                            setAnchorEl(button);
                                            setCopyOkOpen(true);
                                            setTimeout(() => setCopyOkOpen(false), 1000);
                                        });
                                }}>
                                    <ContentCopyIcon/>
                                </IconButton>
                                <Popover
                                    id="copy-popover" open={copyOkOpen} anchorEl={anchorEl}
                                    anchorOrigin={{vertical: 'bottom', horizontal: 'right',}}
                                    onClose={() => {
                                        setCopyOkOpen(false);
                                        setAnchorEl(null);
                                    }}>
                                    <Typography p={1} variant="body2">链接地址已复制</Typography>
                                </Popover>
                            </Box>
                        </DialogTitle>
                        <Box p={2} component={Paper}>
                            <QRCode style={{cursor: 'pointer'}} value={url} size={256}
                                    onClick={() => window.open(url, '_blank')}/>
                        </Box>
                    </Dialog>
                </>}
        </Box>
    );
}

export default Commission;
